# -*- coding: utf-8 -*-
# Copyright © 2024 weidongkl <weidongkx@gmail.com>
import logging
import os
from excavator.utils.jsonutils import read, write
from excavator.utils.output import ExcavatorJobOutput
from excavator.job.base import Job
from excavator.models.pkg import RpmSubject, InstalledRPMs
from excavator.models.report import notify_err
from excavator.group import PrepareGroup

logger = logging.getLogger("excavator.job")


class PrepareRpmSubject(Job):
    group = PrepareGroup
    requires = (InstalledRPMs,)
    provides = (RpmSubject,)

    def run(self, *args, **kwargs):
        ExcavatorJobOutput.info(self.name, "generate rpm-subject based on pkg_change_info.json and  local rpm lists")
        pkg_change_info_file = "/var/lib/excavator/pkg_change_info.json"
        local_pkg_change_info = "/var/lib/excavator/local_pkg_change_info.json"
        """
        [
            {
                "src":[],
                "dst":[]            
            }.
        ]
        """
        try:
            pkg_change_info = read(pkg_change_info_file)
            install_pkgs = InstalledRPMs.get().items
            remove = []
            install = []
            for pkg in install_pkgs:
                for change_info in pkg_change_info:
                    if pkg in change_info["src"]:
                        remove.append(pkg)
                        install.extend(change_info["dst"])
            RpmSubject.create(install=install, remove=remove)
            body = {"remove": remove, "install": install, "db_remove": []}
            write(local_pkg_change_info, body)
        except Exception as e:
            notify_err(e, self.name)
